import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


public class Joke extends HttpServlet {

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		String page = request.getParameter("page");
		request.getSession().setAttribute("page", page);
		String httpUrl = "http://apis.baidu.com/showapi_open_bus/showapi_joke/joke_text";
		String httpArg = "page="+page;
		String jsonResult = SearchHelp.request(httpUrl, httpArg);
//		System.out.println(jsonResult);
		JSONObject  dataJson=new JSONObject(jsonResult);
		JSONArray jokeList = dataJson.getJSONObject("showapi_res_body").getJSONArray("contentlist");
		for(int i =1; i<jokeList.length();i++){
			String title = jokeList.getJSONObject(i).getString("title");
			request.getSession().setAttribute("title"+i, title);
			String text = jokeList.getJSONObject(i).getString("text");
			request.getSession().setAttribute("text"+i, text);
			String ct = jokeList.getJSONObject(i).getString("ct");
			request.getSession().setAttribute("ct"+i, ct);
		}
		response.sendRedirect("joke.jsp");

		
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request,response);
	}

}
